import { useTranslation } from 'react-i18next';
import moment from 'moment';
import {
  Grid,
  Typography,
  Box,
  TableContainer,
  TableHead,
  TableBody,
  TableRow,
  TableCell,
  useTheme
} from '@mui/material';

// Icons
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
import WarningAmberIcon from '@mui/icons-material/WarningAmber';
import ErrorOutlineIcon from '@mui/icons-material/ErrorOutline';
import EventIcon from '@mui/icons-material/Event';
import AutorenewIcon from '@mui/icons-material/Autorenew';

// Styled Components
import {
  StyledPaper,
  StyledAppButton,
  StyledTable
} from 'components/objects/StyledComponents';

/**
 * UserInfoDesktop component that displays user details and subscription status in table view
 * 
 * @param {Object} props
 * @param {Object} props.user - User object containing email and account data
 * @param {Object} props.subscription - Current subscription object
 * @param {Function} props.hasFailedPayment - Utility function to check for failed payments
 * @param {Function} props.onUpdatePayment - Optional handler for payment update button
 */
const UserInfoDesktop = ({
  user,
  subscription,
  hasFailedPayment,
  onUpdatePayment
}) => {
  const { t } = useTranslation();
  const theme = useTheme();
  const isDarkMode = theme.palette.mode === 'dark';

  // Format date from Unix timestamp
  const formatDate = (unixTimestamp) => {
    return moment.unix(unixTimestamp).format("DD/MM/YYYY");
  };

  // Format date from ISO string
  const formatISODate = (isoDate) => {
    return moment(isoDate).format("DD/MM/YYYY");
  };

  // Check for payment failures
  const hasPaymentFailed = hasFailedPayment(user.account);
  const isPastDue = subscription?.status === "past_due";

  // Custom styled header cell
  const HeaderCell = ({ children, icon, color, ...props }) => (
    <TableCell 
      {...props} 
      sx={{ 
        color: color ? theme.palette[color].main : 'inherit',
        pt: 2,
        pb: 1,
        ...(props?.sx || {})
      }}
    >
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        {icon}
        <Typography variant="subtitle2" color={color ? `${color}.main` : 'inherit'}>
          {children}
        </Typography>
      </Box>
    </TableCell>
  );

  return (
    <Grid item xs={12}>
      <StyledPaper darkMode={isDarkMode} sx={{ p: 3 }}>
        {/* User Email Header */}
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
          <AccountCircleIcon 
            color="primary" 
            sx={{ fontSize: 32, mr: 2 }}
          />
          <Typography variant="h5" component="h1">
            {user.email}
          </Typography>
        </Box>

        {/* Table View */}
        <TableContainer>
          <StyledTable darkMode={isDarkMode}>
            <TableHead>
              <TableRow>
                {hasPaymentFailed ? (
                  <>
                    <HeaderCell 
                      icon={<WarningAmberIcon color="error" sx={{ fontSize: 20 }} />}
                      color="error"
                    >
                      {t("dashboardPage.failedPaymentAt")}
                    </HeaderCell>
                    <HeaderCell 
                      icon={<ErrorOutlineIcon color="error" sx={{ fontSize: 20 }} />}
                      color="error"
                    >
                      {t("dashboardPage.subscriptionDeactivateOn")}
                    </HeaderCell>
                  </>
                ) : subscription?.canceled_at ? (
                  <HeaderCell 
                    icon={<EventIcon color="warning" sx={{ fontSize: 20 }} />}
                    color="warning"
                  >
                    {t("dashboardPage.subscriptionDeactivateOn")}
                  </HeaderCell>
                ) : (
                  <HeaderCell 
                    icon={<AutorenewIcon color="success" sx={{ fontSize: 20 }} />}
                    color="success"
                  >
                    {t("dashboardPage.subscriptionRenewOn")}
                  </HeaderCell>
                )}
                
                {isPastDue && (
                  <HeaderCell 
                    icon={<WarningAmberIcon color="error" sx={{ fontSize: 20 }} />}
                    color="error"
                  >
                    {t("dashboardPage.checkYourPayments")}
                  </HeaderCell>
                )}
              </TableRow>
            </TableHead>
            <TableBody>
              <TableRow>
                {hasPaymentFailed ? (
                  <>
                    <TableCell sx={{ color: theme.palette.error.main }}>
                      {formatISODate(user.account.paymentFailedFirstAt)}
                    </TableCell>
                    <TableCell sx={{ color: theme.palette.error.main }}>
                      {formatISODate(user.account.paymentFailedSubscriptionEndsAt)}
                    </TableCell>
                  </>
                ) : (
                  <TableCell 
                    sx={{ 
                      color: subscription?.canceled_at 
                        ? theme.palette.warning.main 
                        : theme.palette.success.main 
                    }}
                  >
                    {formatDate(subscription?.current_period_end)}
                  </TableCell>
                )}
                
                {isPastDue && (
                  <TableCell>
                    <StyledAppButton 
                      darkMode={isDarkMode}
                      variant="outlined" 
                      color="error" 
                      size="small"
                      onClick={onUpdatePayment}
                      sx={{ py: 0.5 }}
                    >
                      {t("dashboardPage.updatePayment")}
                    </StyledAppButton>
                  </TableCell>
                )}
              </TableRow>
            </TableBody>
          </StyledTable>
        </TableContainer>
      </StyledPaper>
    </Grid>
  );
};

export default UserInfoDesktop;